package ie.nolantech.gpsg;

import ie.nolantech.util.BetterLocation;
import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

public class GpsLoggerIntentService extends IntentService {

	final static int ONGOING_NOTIFICATION = 1000;
	
	GpsHelper mHelper;
	LocationManager locationManager;
	LocationListener locationListener;
	LocationListener networkLocationListener;
	Location currentLocation;

	private static final String TAG = "GpsLoggerIntentService";
	
	public GpsLoggerIntentService() {
		super(TAG);
	}

	private boolean setCurrentLocation(Location newLocation) {
		BetterLocation bl = new BetterLocation();
		if (bl.isBetterLocation(newLocation, currentLocation)) {
			currentLocation = newLocation;
			return true;

		} else {
			return false;
		}
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
		Log.d(TAG, "onHandleIntent");
		
		
		Notification notification = new Notification(R.drawable.icon, getText(R.string.app_name),
		        System.currentTimeMillis());
		Intent notificationIntent = new Intent(this, GpsGameActivity.class);
		PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
		notification.setLatestEventInfo(this, "hello",
		        "notification message", pendingIntent);
		startForeground(ONGOING_NOTIFICATION, notification);
		
		
		mHelper = new GpsHelper(this);

		locationManager = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);

		locationListener = new LocationListener() {
			public void onLocationChanged(Location location) {
				mHelper.insertPosition(location.getLatitude(),
						location.getLongitude(), location.getSpeed(), "GPS"
								+ (setCurrentLocation(location) ? "Better"
										: "Worse"));
			}

			public void onStatusChanged(String provider, int status,
					Bundle extras) {
			}

			public void onProviderEnabled(String provider) {
			}

			public void onProviderDisabled(String provider) {
			}
		};

		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
				0, locationListener);

	}

	@Override
	public void onDestroy() {
		Log.d(TAG, "Destroy");
		locationManager.removeUpdates(locationListener);
		super.onDestroy();
	}

}
